package com.acmen.easyapi.util;

import com.acmen.easyapi.model.MenuTree;
import com.acmen.easyapi.model.Api;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class ApiMenuTreeUtil {

    private ApiMenuTreeUtil(){

    }


    /**
     * 构造接口菜单树
     * @param apis
     * @return
     */
    public static MenuTree getApiMenuTree(List<Api> apis) {
        MenuTree rootMenuTree = new MenuTree("接口列表");
        rootMenuTree.setApiId("root");
        rootMenuTree.setChildrens(new ArrayList<>());
        for (Api api : apis) {
            String[] modules = api.getModule().split("\\.");
            MenuTree parent = rootMenuTree;
            for(int i=0;i<modules.length;i++){
                String module = modules[i];
                MenuTree menuTree = findMenu(parent,module);
                if(menuTree ==null){
                    menuTree = new MenuTree(module);
                    if(parent.getChildrens()==null){
                        parent.setChildrens(new ArrayList<>());
                    }
                    parent.getChildrens().add(menuTree);
                }
                parent = menuTree;
            }
            if(parent.getChildrens()==null){
                parent.setChildrens(new ArrayList<>());
            }
            String url="/api/"+api.getId();
            String method = api.getRequestMethod();
            if(RequestMethod.DELETE.toString().equals(method)){
                method = "DEL";
            }
            String apiName = "● "+api.getName()+"("+method+")";
            parent.getChildrens().add(new MenuTree(apiName,api.getId(),url,api.getPath(),api.getNo()));
        }
        rootMenuTree.setChildrens(sort(rootMenuTree.getChildrens()));
        return rootMenuTree;
    }

    private static List<MenuTree> sort(List<MenuTree> menuTrees){
        menuTrees = menuTrees.stream().sorted(Comparator.comparing(MenuTree::getSortIndex)).collect(Collectors.toList());
        return menuTrees;
    }

    private static MenuTree findMenu(MenuTree parent, String name){
        if(parent.getChildrens()!=null){
            for(MenuTree menuTree : parent.getChildrens()){
                if(menuTree.getName().equalsIgnoreCase(name)){
                    return menuTree;
                }
            }
        }
        return null;
    }
}
